package com.bookManagerment.controller.reader;

import com.bookManagerment.config.BMSystemProperties;
import com.bookManagerment.entity.Books;
import com.bookManagerment.entity.BorrowBooks;
import com.bookManagerment.entity.Reader;
import com.bookManagerment.service.BookService;
import com.bookManagerment.service.BorrowBookService;
import com.bookManagerment.utils.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Arrays;

@RequestMapping("/reader/borrowBook")
@RestController
public class RBorrowBookController {

    @Autowired
    private BorrowBookService borrowBookService;

    @Autowired
    private BMSystemProperties bmProperties;

    @Autowired
    private BookService bookService;

    //分页查询 并可以带查询参数
    @GetMapping("/{page}/{size}")
    public ResponseEntity<Page<BorrowBooks>> borrowBookByPage(@PathVariable("page") Integer page,
                                                              @PathVariable("size") Integer size,
                                                              BorrowBooks borrowBooks,
                                                              HttpSession session){
        Reader reader = (Reader) session.getAttribute(bmProperties.getReaderSessionName());
        borrowBooks.setRName(reader.getRName());
        return ResponseEntity.ok(borrowBookService.borrowBookByPage(page,size, borrowBooks,true));
    }


    @PostMapping("/{bbId}/{number}")
    public ResponseEntity<Void> saveReserve(@PathVariable("bbId") Integer bbId,@PathVariable("number") String number){

        //查询该书本的书号对应的图书的数量
        Books books = bookService.findBooks(number);
//        int total = books.getTotal()+1;
        int total = books.getTotal();

        //把图书数量+1，更新在库的书本数量
        bookService.updateBooks(number,total);

        //删除借阅表中的信息
        borrowBookService.deleteBook(bbId);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

}
